import { createRouter, createWebHistory } from 'vue-router'
import type { RouteRecordRaw } from 'vue-router'

const routes: RouteRecordRaw[] = [
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/LoginPage.vue'),
    meta: {
      title: '관리자 로그인',
      requiresAuth: false
    }
  },
  {
    path: '/',
    component: () => import('@/layouts/MainLayout.vue'),
    meta: {
      requiresAuth: true
    },
    children: [
      {
        path: '',
        redirect: '/dashboard'
      },
      {
        path: '/dashboard',
        name: 'Dashboard',
        component: () => import('@/views/DashboardPage.vue'),
        meta: {
          title: '시스템 개요',
          requiresAuth: true,
          requiresAdmin: true
        }
      },
      {
        path: '/deposit-management',
        name: 'DepositManagement',
        component: () => import('@/views/DepositManagePage.vue'),
        meta: {
          title: '충전 관리',
          requiresAuth: true
          // 移除 requiresAdmin: true，允许USER角色访问
        }
      },
      {
        path: '/withdraw-management',
        name: 'WithdrawManagement',
        component: () => import('@/views/WithdrawManagePage.vue'),
        meta: {
          title: '출금 관리',
          requiresAuth: true
          // 移除 requiresAdmin: true，允许USER角色访问
        }
      },
      // 회원 관리 라우트
      {
        path: '/member-login',
        name: 'MemberLogin',
        component: () => import('@/views/MemberLoginPage.vue'),
        meta: {
          title: '회원 관리',
          requiresAuth: true
        }
      },
      {
        path: '/join-inquiry',
        name: 'JoinInquiry',
        component: () => import('@/views/JoinInquiryPage.vue'),
        meta: {
          title: '추천인 관리',
          requiresAuth: true,
          requiresAdmin: true
        }
      },
      // 质押管理路由
      {
        path: '/staking-management',
        name: 'StakingManagement',
        component: () => import('@/views/StakingManagePage.vue'),
        meta: {
          title: '스테이킹 원금 관리',
          requiresAuth: true,
          requiresAdmin: true
        }
      },
      // 推荐收益提现管理路由
      {
        path: '/referral-withdraw-management',
        name: 'ReferralWithdrawManagement',
        component: () => import('@/views/ReferralWithdrawManagePage.vue'),
        meta: {
          title: '추천인 수익 출금 관리',
          requiresAuth: true,
          requiresAdmin: true
        }
      },
      // 合作伙伴管理路由
      {
        path: '/partner-management',
        name: 'PartnerManagement',
        component: () => import('@/views/PartnerManagePage.vue'),
        meta: {
          title: '파트너 관리',
          requiresAuth: true,
          requiresAdmin: true
        }
      }
    ]
  }
]

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes
})

// 라우터 가드
router.beforeEach((to, from, next) => {
  const adminToken = localStorage.getItem('admin_token')
  const userType = localStorage.getItem('admin_user_type')

  // 获取管理员角色信息
  let adminRole = ''
  try {
    const userInfo = localStorage.getItem('admin_user')
    if (userInfo) {
      const user = JSON.parse(userInfo)
      adminRole = user.role || ''
    }
  } catch (error) {
    console.error('Failed to parse admin user info:', error)
  }

  // 页面标题设置
  if (to.meta?.title) {
    document.title = `${to.meta.title} - 한국 금융 시스템 관리자`
  }

  // 未登录用户访问需要认证的页面 -> 重定向到登录页
  if (!adminToken && to.meta?.requiresAuth) {
    next('/login')
    return
  }

  // 已登录用户访问登录页 -> 重定向到首页
  if (adminToken && to.path === '/login') {
    if (userType === 'ADMIN') {
      // 合作伙伴重定向到会员列表，其他管理员重定向到 Dashboard
      if (adminRole === 'PARTNER') {
        next('/member-login')
      } else {
        next('/dashboard')
      }
    } else {
      // 推荐人重定向到会员列表
      next('/member-login')
    }
    return
  }

  // 根路径重定向
  if (adminToken && to.path === '/') {
    if (userType === 'ADMIN') {
      // 合作伙伴重定向到会员列表，其他管理员重定向到 Dashboard
      if (adminRole === 'PARTNER') {
        next('/member-login')
      } else {
        next('/dashboard')
      }
    } else {
      // 推荐人重定向到会员列表
      next('/member-login')
    }
    return
  }

  // 权限检查：requiresAdmin 的页面
  if (to.meta?.requiresAdmin) {
    // 普通用户（推荐人）无权访问
    if (userType === 'USER') {
      next('/member-login')
      return
    }
    // 系统设置仅限管理员访问（不包括合作伙伴）
    if (to.path === '/settings' && userType === 'ADMIN' && adminRole === 'PARTNER') {
      next('/member-login')
      return
    }
    // 合作伙伴现在可以访问除系统设置外的所有页面
  }

  next()
})

export default router
